package com.arkisv.log.task;

import com.arkisv.common.model.EventLog;
import com.arkisv.common.util.SystemUtil;
import com.arkisv.log.dao.EventLogMapper;
import com.arkisv.log.util.Global;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class UpdateEventLogTask {
	private long timeout = 10*1000; // 超时时间,10000毫秒

	@Autowired
	private EventLogMapper eventLogDao;

	/**
	 * 每3s执行一次修改操作,超时的记录则删除
	 */
    @Scheduled(cron="0/3 * * * * ?")
	public void updateEventLog() {
        if(Global.CACHE_UPDATE_EVENTLOG_LIST.size() == 0) {
            return;
        }

        SystemUtil.println("等待修改列表(CACHE_UPDATE_EVENTLOG_LIST):" + Global.CACHE_UPDATE_EVENTLOG_LIST);
		List<EventLog> removeEventLogList = new ArrayList<EventLog>();
		for (EventLog eventLog : Global.CACHE_UPDATE_EVENTLOG_LIST) {
			if((System.currentTimeMillis() - eventLog.getCacheTime()) >= timeout) { // 已超时
				// 加入待删除列表
				removeEventLogList.add(eventLog);
				SystemUtil.println("CACHE_UPDATE_EVENTLOG_LIST->超时:" + eventLog);
				continue;
			}

			// 查询数据库是否有记录
            EventLog dbEventLog = eventLogDao.selectByPrimaryKey(eventLog.getEventId());
			if(dbEventLog == null) {
			    continue;
            }

            // 数据已插入,执行修改并从缓存中删除日志记录
            eventLogDao.updateByPrimaryKeySelective(eventLog);
			removeEventLogList.add(eventLog);
			SystemUtil.println("CACHE_UPDATE_EVENTLOG_LIST->已修改:" + eventLog);
		}

		// 删除日志记录
        for (EventLog eventLog : removeEventLogList) {
            Global.CACHE_UPDATE_EVENTLOG_LIST.remove(eventLog);
        }
    }

}
